package org.chz.utils;

public class MatrixUtils {
    public static double[][] transpose(double[][] matrix) {
        int rows = matrix.length;
        int cols = matrix[0].length;

        double[][] transposed = new double[cols][rows];

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                transposed[j][i] = matrix[i][j];
            }
        }

        return transposed;
    }

    public static double moduleLengthOfVector(double[] vector){
        double sum = 0;
        for(int i = 0; i < vector.length; i++){
            sum += vector[i] * vector[i];
        }
        return Math.sqrt(sum);
    }

    public static void unitizationVector(double[] vector) {
        double module = moduleLengthOfVector(vector);
        for (int i = 0; i < vector.length; i++){
            vector[i] = vector[i] / module;
        }
    }

    public static double[][] multiply(double[][] mat1, double[][] mat2){
        int m = mat1.length, n = mat2[0].length;
        double[][] mat = new double[m][n];
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                for(int k = 0; k < mat1[0].length; k++){
                    mat[i][j] += mat1[i][k] * mat2[k][j];
                }
            }
        }
        return mat;
    }


    public static double[][] add(double[][] A, double[][] B) {
        int n = A.length;
        double[][] C = new double[n][n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                C[i][j] = A[i][j] + B[i][j];
            }
        }
        return C;
    }

    public static double[][] subtract(double[][] A, double[][] B) {
        int n = A.length;
        double[][] C = new double[n][n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                C[i][j] = A[i][j] - B[i][j];
            }
        }
        return C;
    }

    public static void printMatrix(double[][] matrix) {
        for (double[] row : matrix) {
            for (double element : row) {
                System.out.print(element + " ");
            }
            System.out.println();
        }
    }
}
